<template>
	<view class="chatroom-detail" :class="{ 'emoji-visible': showEmojiPicker }">
		<!-- 聊天消息列表 -->
		<scroll-view scroll-y class="message-list" :scroll-into-view="scrollToView" :scroll-with-animation="true">
			<view class="message-container">
				<!-- 日期分隔 -->
				<view class="date-divider" v-for="(group, date) in groupedMessages" :key="date">
					<text class="date-text">{{ date }}</text>

					<!-- 消息项 -->
					<view class="message-item" :class="{ 'self': msg.isSelf }" v-for="msg in group" :key="msg.messageId"
						:id="'msg-' + msg.messageId">
						<image class="avatar" :src="msg.avatar" mode="aspectFill" />
						<view class="message-content">
							<view class="user-info" v-if="!msg.isSelf">
								<text class="nickname">{{ msg.nickname }}</text>
							</view>
							<view class="bubble-wrapper">
								<view class="bubble" :class="{ 'self-bubble': msg.isSelf }">
									<!-- 文本消息 -->
									<text class="text" v-if="msg.type === 'text'">{{ msg.content }}</text>

									<!-- 图片消息 -->
									<image v-else-if="msg.type === 'image'" class="image-msg" :src="msg.content"
										mode="aspectFill" @click="previewImage(msg.content)" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部输入栏 -->
		<view class="input-bar">
			<view class="input-wrapper">
				<!-- 表情按钮 -->
				<view class="icon-btn emoji-btn" @click="showEmojiPicker = !showEmojiPicker">
					<up-icon name="smile-fill" size="26" :color="showEmojiPicker ? '#667eea' : '#666'"></up-icon>
				</view>

				<!-- 输入框容器 -->
				<view class="input-container">
					<input class="input" v-model="inputValue" placeholder="说点什么吧..." :adjust-position="true"
						@confirm="handleSendMessage" />
				</view>

				<!-- 图片按钮 -->
				<view class="icon-btn image-btn" @click="handleChooseImage">
					<up-icon name="photo-fill" size="26" color="#666"></up-icon>
				</view>

				<!-- 发送按钮 -->
				<view class="send-btn" :class="{ 'active': inputValue.trim() && !sending, 'sending': sending }"
					@click="handleSendMessage">
					{{ sending ? '发送中' : '发送' }}
				</view>
			</view>
		</view>

		<!-- 表情选择器 -->
		<view class="emoji-picker" v-if="showEmojiPicker">
			<view class="emoji-list">
				<text class="emoji-item" v-for="emoji in emojiList" :key="emoji" @click="handleSelectEmoji(emoji)">
					{{ emoji }}
				</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		mockGetChatroomMessages,
		mockSendMessage
	} from '../../server/mock.js';
	import websocket from '../../utils/websocket.js';

	// 路由参数
	const roomId = ref(0);

	// 响应式数据
	const messages = ref([]);
	const inputValue = ref('');
	const scrollToView = ref('');
	const showEmojiPicker = ref(false);
	const loading = ref(true);
	const sending = ref(false); // 发送中状态
	const userInfo = ref(null); // 当前用户信息

	// 表情列表
	const emojiList = ref([
		'😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂',
		'🙂', '😉', '😊', '😇', '🥰', '😍', '🤩', '😘',
		'😗', '😚', '😙', '🥲', '😋', '😛', '😜', '🤪',
		'😝', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐',
		'😑', '😶', '😏', '😒', '🙄', '😬', '😮‍💨', '🤥',
		'😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕',
		'🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '🤯',
		'🤠', '🥳', '🥸', '😎', '🤓', '🧐', '😕', '😟',
		'🙁', '☹️', '😮', '😯', '😲', '😳', '🥺', '😦',
		'😧', '😨', '😰', '😥', '😢', '😭', '😱', '😖',
		'😣', '😞', '😓', '😩', '😫', '🥱', '👍', '👎',
		'👏', '🙌', '👋', '🤝', '🙏', '💪', '❤️', '💕'
	]);

	/**
	 * 处理接收到的WebSocket消息
	 */
	const handleWebSocketMessage = (data) => {
		console.log('收到消息:', data);
		
		// 判断是否为自己发送的消息
		const currentUserId = String(userInfo.value?.userId || '');
		const messageSenderId = String(data.senderId || '');
		const isSelf = currentUserId === messageSenderId;
		
		// 将接收到的消息转换为前端消息格式
		const newMessage = {
			messageId: data.messageId || Date.now(),
			type: data.type === 'chat' ? 'text' : (data.type || 'text'),
			content: data.content,
			senderId: messageSenderId,
			nickname: data.senderName || '未知用户',
			avatar: data.avatar || 'https://picsum.photos/200/200?random=' + Math.random(),
			isSelf: isSelf,
			createTime: data.createTime || Date.now()
		};

		// 添加到消息列表
		messages.value.push(newMessage);

		// 滚动到底部
		nextTick(() => {
			scrollToBottom();
		});
	};

	/**
	 * 处理WebSocket错误
	 */
	const handleWebSocketError = (err) => {
		console.error('WebSocket错误:', err);
		uni.showToast({
			title: err.message || '连接错误',
			icon: 'none'
		});
	};

	/**
	 * 处理WebSocket连接成功
	 */
	const handleWebSocketConnect = () => {
		console.log('WebSocket连接成功');
		// 连接成功后发送加入房间消息
		if (userInfo.value && roomId.value) {
			const joinMessage = {
				type: 'chat',
				content: '加入房间',
				receiverType: 'room',
				receiverId: roomId.value,
				senderId: String(userInfo.value.userId),
				senderName: userInfo.value.nickname || '用户'
			};
			websocket.send(joinMessage);
		}
	};

	/**
	 * 初始化WebSocket连接
	 */
	const initWebSocket = () => {
		// 设置WebSocket地址
		websocket.setUrl('ws://localhost:8900/chat');
		
		// 注册回调
		websocket.onMessage(handleWebSocketMessage);
		websocket.onError(handleWebSocketError);
		websocket.onConnect(handleWebSocketConnect);
		
		// 初始化连接（不发送初始消息，在连接成功后再发送）
		websocket.init();
	};

	// 页面加载
	onLoad((options) => {
		if (options.roomId) {
			roomId.value = parseInt(options.roomId);
			
			// 获取用户信息
			const savedUserInfo = uni.getStorageSync('userInfo');
			if (savedUserInfo) {
				userInfo.value = savedUserInfo;
			} else {
				// 如果没有用户信息，使用默认值（实际应该跳转到登录页）
				userInfo.value = {
					userId: 'user-' + Math.random().toString(36).substr(2, 9),
					nickname: '用户' + Math.random().toString(36).substr(2, 4)
				};
				uni.showToast({
					title: '未登录，使用临时身份',
					icon: 'none'
				});
			}

			// 初始化WebSocket
			initWebSocket();
			
			// 加载历史消息
			loadMessages();
		}
	});

	// 页面卸载时关闭WebSocket连接
	onUnmounted(() => {
		websocket.close();
	});

	/**
	 * 加载消息列表
	 */
	const loadMessages = async () => {
		loading.value = true;

		try {
			const res = await mockGetChatroomMessages(roomId.value);

			if (res.code === 200) {
				messages.value = res.data || [];

				// 滚动到底部
				nextTick(() => {
					scrollToBottom();
				});
			}
		} catch (error) {
			console.error('加载消息失败:', error);
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 按日期分组消息
	 */
	const groupedMessages = computed(() => {
		const groups = {};

		messages.value.forEach(msg => {
			const date = formatDate(msg.createTime);
			if (!groups[date]) {
				groups[date] = [];
			}
			groups[date].push(msg);
		});

		return groups;
	});

	/**
	 * 发送消息（统一处理回车和点击）
	 */
	const handleSendMessage = async () => {
		const content = inputValue.value.trim();

		// 防止重复发送
		if (!content || sending.value) return;
		
		// 检查用户信息
		if (!userInfo.value) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			return;
		}

		// 检查WebSocket连接状态
		if (!websocket.isConnected()) {
			uni.showToast({
				title: '连接未建立，请稍候',
				icon: 'none'
			});
			return;
		}

		// 设置发送中状态
		sending.value = true;
		
		// 构建发送消息参数（符合后端要求）
		const sendData = {
			type: 'chat',
			content: content,
			receiverType: 'room',
			receiverId: roomId.value,
			senderId: String(userInfo.value.userId),
			senderName: userInfo.value.nickname || '用户'
		};

		try {
			// 通过WebSocket发送消息
			const success = websocket.send(sendData);

			if (success) {
				// 清空输入框
				inputValue.value = '';

				// 关闭表情选择器
				showEmojiPicker.value = false;

				// 消息会通过WebSocket广播回来，在handleWebSocketMessage中统一渲染
			} else {
				uni.showToast({
					title: '发送失败，请重试',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('发送消息失败:', error);
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			});
		} finally {
			// 重置发送状态
			sending.value = false;
		}
	};

	/**
	 * 选择图片
	 */
	const handleChooseImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				const tempFilePath = res.tempFilePaths[0];

				try {
					uni.showLoading({
						title: '发送中...'
					});

					// 这里应该上传图片到服务器，获取图片URL
					// 暂时使用临时路径模拟
					const uploadRes = await mockSendMessage({
						roomId: roomId.value,
						type: 'image',
						content: tempFilePath
					});

					uni.hideLoading();

					if (uploadRes.code === 200) {
						messages.value.push(uploadRes.data);

						nextTick(() => {
							scrollToBottom();
						});
					} else {
						uni.showToast({
							title: '发送失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('发送图片失败:', error);
					uni.showToast({
						title: '发送失败',
						icon: 'none'
					});
				}
			}
		});
	};

	/**
	 * 选择表情
	 */
	const handleSelectEmoji = (emoji) => {
		inputValue.value += emoji;
		showEmojiPicker.value = false;
	};

	/**
	 * 预览图片
	 */
	const previewImage = (url) => {
		const imageUrls = messages.value
			.filter(msg => msg.type === 'image')
			.map(msg => msg.content);

		uni.previewImage({
			current: url,
			urls: imageUrls
		});
	};

	/**
	 * 滚动到底部
	 */
	const scrollToBottom = () => {
		if (messages.value.length > 0) {
			const lastMsg = messages.value[messages.value.length - 1];
			scrollToView.value = 'msg-' + lastMsg.messageId;
		}
	};

	/**
	 * 格式化日期
	 */
	const formatDate = (timestamp) => {
		const date = new Date(timestamp);
		const now = new Date();
		const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
		const msgDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());

		if (msgDate.getTime() === today.getTime()) {
			return '今天';
		} else if (msgDate.getTime() === yesterday.getTime()) {
			return '昨天';
		} else {
			return `${date.getMonth() + 1}月${date.getDate()}日`;
		}
	};
</script>

<style lang="scss" scoped>
	@import '../../styles/variables.scss';
	@import '../../styles/mixins.scss';

	.chatroom-detail {
		height: 100vh;
		background: linear-gradient(180deg, #f5f7fa 0%, #e8ecf1 100%);
		box-sizing: border-box;
		overflow: hidden;
	}

	// 消息列表
	.message-list {
		height: calc(100vh - 60px);
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		padding-bottom: $spacing-base;
		box-sizing: border-box;
		transition: height $transition-fast;
	}

	// 当表情选择器显示时，减少消息列表高度
	.chatroom-detail.emoji-visible {
		.message-list {
			height: calc(100vh - 60px - 220px);
		}
	}

	.message-container {
		padding: $spacing-lg $spacing-base;
	}

	// 日期分隔
	.date-divider {
		.date-text {
			display: inline-block;
			margin: $spacing-lg auto;
			padding: $spacing-xs $spacing-base;
			text-align: center;
			font-size: $font-xs;
			color: $text-secondary;
			background: rgba(0, 0, 0, 0.05);
			border-radius: $radius-lg;
			box-sizing: border-box;
			width: auto;
			position: relative;
			left: 50%;
			transform: translateX(-50%);
		}
	}

	// 消息项
	.message-item {
		display: flex;
		margin-bottom: $spacing-lg;
		padding: 0 $spacing-xs;
		animation: messageSlideIn 0.3s ease-out;

		.avatar {
			width: 42px;
			height: 42px;
			border-radius: 50%;
			flex-shrink: 0;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
			border: 2px solid #fff;
		}

		.message-content {
			flex: 1;
			margin-left: $spacing-sm;
			max-width: calc(100% - 60px);

			.user-info {
				margin-bottom: $spacing-xs;
				padding-left: 2px;

				.nickname {
					font-size: $font-xs;
					color: $text-secondary;
					font-weight: $font-medium;
				}
			}

			.bubble-wrapper {
				display: flex;
				align-items: flex-end;

				.bubble {
					position: relative;
					max-width: 280px;
					padding: 10px 14px;
					background: #fff;
					border-radius: 18px;
					border-top-left-radius: 4px;
					box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

					// 气泡尾巴
					&::before {
						content: '';
						position: absolute;
						left: -6px;
						top: 0;
						width: 12px;
						height: 12px;
						background: #fff;
						border-radius: 0 0 12px 0;
						transform: skewX(-15deg);
					}

					.text {
						font-size: $font-base;
						color: $text-primary;
						line-height: 1.6;
						word-break: break-word;
						white-space: pre-wrap;
					}

					.image-msg {
						display: block;
						max-width: 220px;
						max-height: 220px;
						min-width: 100px;
						min-height: 100px;
						border-radius: $radius-base;
						background: $bg-page;
					}

					&.self-bubble {
						background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
						border-top-left-radius: 18px;
						border-top-right-radius: 4px;

						// 自己的气泡尾巴
						&::before {
							left: auto;
							right: -6px;
							border-radius: 0 0 0 12px;
							background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
							transform: skewX(15deg);
						}

						.text {
							color: #fff;
						}
					}
				}
			}
		}

		// 自己发送的消息
		&.self {
			flex-direction: row-reverse;

			.message-content {
				margin-left: 0;
				margin-right: $spacing-sm;

				.user-info {
					text-align: right;
					padding-left: 0;
					padding-right: 2px;
				}

				.bubble-wrapper {
					justify-content: flex-end;
				}
			}
		}
	}

	// 消息滑入动画
	@keyframes messageSlideIn {
		from {
			opacity: 0;
			transform: translateY(10px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	// 底部输入栏
	.input-bar {
		height: 60px;
		background: #fff;
		border-top: 1px solid #e5e5e5;
		padding: 8px 12px;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 100;

		.input-wrapper {
			display: flex;
			align-items: center;
			gap: 10px;
			height: 100%;

			// 图标按钮样式（表情和图片）
			.icon-btn {
				width: 36px;
				height: 36px;
				flex-shrink: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				cursor: pointer;
				transition: all $transition-fast;

				&:active {
					transform: scale(0.9);
				}
			}

			// 输入框容器
			.input-container {
				flex: 1;
				height: 36px;
				background: #f5f5f5;
				border: 1.5px solid #d8d8d8;
				border-radius: 18px;
				overflow: hidden;
				transition: all $transition-fast;

				&:focus-within {
					background: #fff;
					border-color: #667eea;
					box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
				}

				.input {
					width: 100%;
					height: 100%;
					padding: 0 16px;
					background: transparent;
					border: none;
					font-size: 15px;
					color: $text-primary;
					line-height: 36px;

					&::placeholder {
						color: #999;
					}
				}
			}

			// 发送按钮
			.send-btn {
				padding: 0 18px;
				height: 32px;
				line-height: 32px;
				background: #f5f5f5;
				color: #999;
				border-radius: 16px;
				font-size: 14px;
				font-weight: $font-medium;
				cursor: pointer;
				transition: all $transition-base;
				text-align: center;
				flex-shrink: 0;

				&.active {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: #fff;
					box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
				}

				&.sending {
					background: #d0d0d0;
					color: #999;
					cursor: not-allowed;
					opacity: 0.6;
				}

				&:active.active {
					transform: scale(0.95);
				}
			}
		}
	}

	// 表情选择器
	.emoji-picker {
		height: 220px;
		background: #fff;
		border-top: 1px solid rgba(0, 0, 0, 0.05);
		overflow-y: auto;
		box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.04);
		position: fixed;
		bottom: 60px;
		left: 0;
		right: 0;
		z-index: 99;
		box-sizing: border-box;

		.emoji-list {
			display: grid;
			grid-template-columns: repeat(8, 1fr);
			gap: $spacing-xs;
			padding: $spacing-base;

			.emoji-item {
				width: 100%;
				aspect-ratio: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28px;
				cursor: pointer;
				border-radius: $radius-base;
				transition: all $transition-fast;

				&:active {
					background: rgba(102, 126, 234, 0.1);
					transform: scale(1.2);
				}
			}
		}
	}

	// 滚动条美化（仅在支持的浏览器中生效）
	.message-list::-webkit-scrollbar {
		width: 4px;
	}

	.message-list::-webkit-scrollbar-track {
		background: transparent;
	}

	.message-list::-webkit-scrollbar-thumb {
		background: rgba(0, 0, 0, 0.1);
		border-radius: 2px;
	}

	.emoji-picker::-webkit-scrollbar {
		width: 4px;
	}

	.emoji-picker::-webkit-scrollbar-track {
		background: transparent;
	}

	.emoji-picker::-webkit-scrollbar-thumb {
		background: rgba(0, 0, 0, 0.1);
		border-radius: 2px;
	}
</style>

<style lang="scss">
	// 页面级别样式（非 scoped）
	page {
		height: 100%;
		overflow: hidden;
	}
</style>